<template>
  <div id="ezuikitBox">
    <div class="right">
      <div class="video-switch">
        <div class="video-switch-tab">
          <div class="video-switch-tab-btn">

          </div>

        </div>
      </div>
      <div id="playWnd" style="width: 900px;height:500px;text-align: center;"></div>
    </div>


  </div>
</template>
<!--<script type="text/javascript" src="./jsWebControl-1.0.0.min.js"></script>-->
<script>
  import Vue from 'vue'
  import axios from "axios";

  var oWebControl = null;
  var accessToken = '';

  /**
   * video 初始化及配置
   * @param {*video挂载的dom id} id
   * @param {*连接成功的回调} cbConnectSuccess
   * @param {*连接报错的回调} cbConnectError
   * @param {*连接关闭的回调} cbConnectClose
   */
  function WebControlInit(id, cbConnectSuccess, cbConnectError, cbConnectClose) {
    return new WebControl({
      szPluginContainer: id,
      iServicePortStart: 14510, // 对应 LocalServiceConfig.xml 中的ServicePortStart值
      iServicePortEnd: 14519, // 对应 LocalServiceConfig.xml 中的ServicePortEnd值
      cbConnectSuccess: cbConnectSuccess,
      cbConnectError: cbConnectError,
      cbConnectClose: cbConnectClose,
    });
  }

  /**
   * 离开页面时调用 断开链接的方法
   * @param {*视频插件实例} oWebControl
   */

// 监听视频控件的事件
  function cbIntegrationCallBack(oData) {
    if (oData.responseMsg.eventName === 'FireTransFunction') {
      // 如果视频控件需要请求服务端数据，这里可以处理透传逻辑
    }
  }

  function cbConnectSuccess() {
    // 设置窗口控制回调
    oWebControl.JS_SetWindowControlCallback({
      cbIntegrationCallBack: cbIntegrationCallBack,
    });
    //创建视频窗口
    oWebControl
      .JS_StartService('window', {
        dllPath: './chain/cloudTransform.dll',
      })
      .then(function () {
        oWebControl.JS_CreateWnd('playWnd', 900, 500).then(function () {
          console.log('JS_CreateWnd success');
        });
      });
  }

  function cbConnectError() {
    console.log('cbConnectError');
    oWebControl = null;
    console.error('确认本地进程是否已安装并开启成功！');
  }

  function cbConnectClose(bNormalClose) {
    // 连接异常断开：bNormalClose = false
    // JS_Disconnect正常断开：bNormalClose = true
    console.log('cbConnectClose');
    oWebControl = null;
  }

  //销毁视频控件
  function WebControlDistory() {
    // var bIE = !!window.ActiveXObject || 'ActiveXObject' in window // 是否为IE浏览器
    if (oWebControl != null) {
      oWebControl.JS_DestroyWnd().then(
        function () {
          console.log('JS_DestroyWnd');
        },
        function () {
        }
      );
      oWebControl.JS_StopService('window').then(function () {
        oWebControl.JS_Disconnect().then(
          function () {

            console.log('JS_Disconnect');
          },
          function () {
          }
        );
      });
    }
  }

  window.onscroll = function () {
    if (oWebControl != null) {
      oWebControl.JS_Resize(900, 500);
    }
  };
  window.onresize = function () {
    if (oWebControl != null) {
      oWebControl.JS_Resize(900, 500);
    }
  };

  window.onunload = function () {
    try {
      oWebControl.JS_HideWnd();
      WebControlDistory();
    } catch (error) {
      console.error(error);
    }
  };
  window.onpagehide = function () {
    try {
      oWebControl.JS_HideWnd();
    } catch (error) {
      console.error(error);
    }
  };
  var limitStart = parseInt(new Date('2021-07-29T16:01:00').getTime() / 1000).toString();
  var limitEnd = parseInt(new Date('2021-07-29T17:01:30').getTime() / 1000).toString();
  import {photoGetLive} from '@/services/model/user'

  export default {
    data() {
      return {
        appKey: 'ca8b39308d3a4dc0aa7fc79c5987483c',
        ezvizToken: 'at.chy6at0z3s6jb7tv4h7szmz90xsuogew-5j3kgaq825-1952mn4-ncpx1fzaz',
        deviceSerial: 'J99015654',
        channelNo: '1',
        deviceClass: '0',
        platformId: '',
        startTime: '',
        endTime: '',
        layout: 1,
        switchVideo: 0, // 0实时预览 1录像回放
        callbackMessage: '', //显示回调信息
        tips: '调用成功',
        successTip: false,
        tipsShow: false,
      };
    },
    name: "HelloWorld",
    methods: {
      //  控制云台开始
      PTZstart(direction, speed) {
        var _this = this
        axios({
          // 创建请求时使用的方法
          method: 'post', // 默认是 get
          // 将自动加在 url 前
          baseURL: 'https://open.ys7.com/api/lapp/device/ptz/start',

          transformRequest: [function (data) {
            return data;
          }],

          // 在传递给 then/catch 前，修改响应数据
          transformResponse: [function (data) {
            // 对 data 进行任意转换处理
            return data;
          }],
          // 与请求一起发送的 URL 参数
          params: {
            accessToken: this.form.accessToken,
            deviceSerial: this.form.deviceSerial,
            channelNo: this.form.channelNo,
            direction: direction,
            speed: speed
          },
        }).then(function (res) {
          let ress = JSON.parse(res.data)
          if (ress.code !== '200') {
            _this.$message.error(ress.msg)
          }
        }).catch(function (err) {
        });
      },
      //  控制云台停止，
      PTZStop(direction, speed) {
        axios({
          // 创建请求时使用的方法
          method: 'post', // 默认是 get
          // 将自动加在 url 前
          baseURL: 'https://open.ys7.com/api/lapp/device/ptz/stop',
          transformRequest: [function (data) {
            return data;
          }],

          // 在传递给 then/catch 前，修改响应数据
          transformResponse: [function (data) {
            // 对 data 进行任意转换处理
            return data;
          }],
          // 与请求一起发送的 URL 参数
          params: {
            accessToken: this.form.accessToken,
            deviceSerial: this.form.deviceSerial,
            channelNo: this.form.channelNo,
            direction: direction,
          },
        }).then(function (response) {
        }).catch(function (error) {
        });
      },

      //  镜头翻转
      mirror(command) {
        axios({
          // 创建请求时使用的方法
          method: 'post', // 默认是 get
          // 将自动加在 url 前
          baseURL: 'https://open.ys7.com/api/lapp/device/ptz/mirror',
          transformRequest: [function (data) {
            return data;
          }],

          // 在传递给 then/catch 前，修改响应数据
          transformResponse: [function (data) {
            // 对 data 进行任意转换处理
            return data;
          }],
          // 与请求一起发送的 URL 参数
          params: {
            accessToken: this.form.accessToken,
            deviceSerial: this.form.deviceSerial,
            channelNo: this.form.channelNo,
            command: command,
          },
        }).then(function (response) {
        }).catch(function (error) {
        });
      },
      //停止
      stop() {

        var str = parseInt(0);
        oWebControl.JS_RequestInterface({
          funcName: 'StopPlay',
          arguments: encodeURI(
            JSON.stringify({
              response: {
                code: 0,
                message: null,
                data: {
                  wndId: str //传入1表示停止窗口1，传入-1表示停止当前活动窗口
                }
              },
            })
          ),
        })
      },
      switchTo(num) {
        let self = this;
        this.switchVideo = num;
        if (oWebControl) {
          oWebControl
            .JS_RequestInterface({
              funcName: 'ChangeModel',
              arguments: encodeURI(
                JSON.stringify({
                  model: num,
                })
              ),
            })
            .then(function (oData) {
              self.playVideo();
            });
        }
      },
      /**
       * 设置视频初始化参数
       */
      async initVideo(id) {
        let res = await photoGetLive({id: id})
        this.form = res.data
        let self = this;
        self.ezvizToken = this.form.accessToken
        self.deviceSerial = this.form.deviceSerial
        if (!self.appKey || !self.ezvizToken) {
          self.showTips(false, '请输入appkey和token');
          return;
        }
        // 初始化入参
        let argumentsPram = {
          layout: +self.layout,
          userName: "",
          waterMark: "1",
          iWndType: 0,
          intelligenceEnable: 1,
          isRecord: 1,
          isSetPos: 1,
          motionDetectEnable: 0,
          playBackAlarmOverlyingEnable: 0,
          response: {
            code: 0,
            message: null,
            data: {
              appKey: self.appKey,
              ezvizToken: self.ezvizToken,
              videoLevel: 0,
              logLevel: 3,
              showMainTool: 1,
              showSubTool: 1,
              waterMark: "",
              userName: "",
              platformId: self.platformId,
            },
          },
        };
        console.log('初始化入参', argumentsPram);
        // 调用视频控件初始化方法
        oWebControl
          .JS_RequestInterface({
            funcName: 'Init',
            arguments: encodeURI(JSON.stringify(argumentsPram)),
          })
          .then(function (oData) {
            self.showTips(true, '视频初始化成功！');
            self.playVideo()
          });

      },
      //拍照
      capturePicture() {
        let data = null;
        oWebControl.JS_RequestInterface({
          funcName: 'CaptureJPGEx',
          arguments: encodeURI(
            JSON.stringify({
              response: {
                code: 0,
                message: null,
                data: data,
              },
            })
          ),
        })
      },
      startSave() {
        var num = parseInt(0);
        oWebControl.JS_RequestInterface({
          funcName: 'StartRecord',
          arguments: encodeURI(
            JSON.stringify({
              response: {
                code: 0,
                message: null,
                data: {
                  wndId: num
                }
              },
            })
          ),
        })

      },

      stopSave() {
        var num = parseInt(0);
        oWebControl.JS_RequestInterface({
          funcName: 'StopRecord',
          arguments: encodeURI(
            JSON.stringify({
              response: {
                code: 0,
                message: null,
                data: {
                  wndId: num
                }
              },
            })
          ),
        })

      },
      /**
       * 播放门店视频
       */
      playVideo() {
        let self = this;
        if (!self.deviceSerial || !self.channelNo) {
          self.showTips(false, '请输入设备序列号和通道号');
          return;
        }
        // 预览入参
        let argumentsPram = {
          response: {
            code: 0,
            message: null,
            data: {
              deviceSerial: self.deviceSerial,
              channelCode: self.channelNo,
              channelNo: +self.channelNo,
              codeIsEncrypt: 0,
              validateCode: "",
              deviceClass: self.deviceClass,
              deviceType: "",
              //deviceType:"10240",
              channelId: "",
              channelName: "",
              storeName: "",
              storeId: "",
              startTime: '',
              endTime: '',
              //Limited_start:limitStart,
              //Limited_end:limitEnd,
            },
          },
        };
        if (self.deviceClass === '1') { // 国标协议对应的两个字段
          argumentsPram.response.data.channelCode = self.channelNo
          argumentsPram.response.data.platformId = self.platformId
        } else { // 海康协议对应的一个字段
          argumentsPram.response.data.channelNo = +self.channelNo
        }
        // 回放时对应的两个字段
        if (this.switchVideo === 1) {
          if (this.startTime)
            argumentsPram.response.data.startTime = this.startTime;
          if (this.endTime) argumentsPram.response.data.endTime = this.endTime;
        }
        console.log('预览/回放入参', argumentsPram);
        // 调用视频控件预览方法
        oWebControl
          .JS_RequestInterface({
            funcName: this.switchVideo === 0 ? 'StartPreview' : 'StartPlayback',
            arguments: encodeURI(JSON.stringify(argumentsPram)),
          })
          .then(function (oData) {
            self.showTips(true, '预览/回放成功！');
          });
      },
      /**
       * 设置事件回调信息
       */

      showTips: function (status, message) {
        let self = this;
        this.successTip = status;
        this.tips = message;
        this.tipsShow = true;
        setTimeout(function () {
          self.tipsShow = false;
        }, 1000);
      },
      /**
       * 隐藏视频
       */
      hideVideo: function () {
        oWebControl.JS_HideWnd();
      },
      /**
       * 显示视频
       */
      showVideo() {
        oWebControl.JS_ShowWnd();
      },

      // 设置清晰度
      testVidelLevel() {
        var num = parseInt(prompt('请输入窗口ID'));
        var level = parseInt(prompt('请输入清晰度，0：流畅 1：均衡 2：高品质 3：超清'));
        oWebControl.JS_RequestInterface({
          funcName: 'SetVideoLevel',
          arguments: encodeURI(
            JSON.stringify({
              response: {
                code: 0,
                message: null,
                data: {
                  wndId: num,
                  level: level //0：流畅 1：均衡 2：高品质 3：超清
                }
              },
            })
          ),
        })

      },
      makeOWebControl() {
        if (oWebControl == null) {
          oWebControl = WebControlInit(
            'playWnd',
            cbConnectSuccess,
            cbConnectError,
            cbConnectClose
          );
          return
        } else {
          WebControlDistory()
        }
      }
    },
    computed: {
      switchLineStyle: function () {
        if (this.switchVideo === 0) {
          return {
            transform: 'translateX(0px)',
          };
        }
        return {
          transform: 'translateX(88px)',
        };
      },
    },
    activated() {
    },
    deactivated() {
      WebControlDistory()

      oWebControl = null

    }
  }
</script>

